<template>
  <div ref="chartRef" class="chart-container" :style="{ height: '71%' }"></div>
</template>
 
<script setup>
import { ref, onMounted, onBeforeUnmount, watch } from "vue";
import * as echarts from "echarts";
import stImage from "@/assets/imgs/st.png"; // 保留原导入，但未在组件中使用

// 定义 props
const props = defineProps({
  chartData: {
    type: Object,
    default: () => ({}),
  },
});

// 初始化 ref
const chartRef = ref(null);
let chart = null;
let timer = null;

// 图表配置数据
let xData = props.chartData.dataX;
let tabType = localStorage.getItem("tabType");
let color = [];
if (tabType == 1) {
  color = [
    "rgba(150, 211, 255, 1)",
    "rgba(91, 143, 255, 1)",
    "rgba(118, 239, 209, 1)",
    "rgba(255, 233, 110, 1)",
    "rgba(150, 211, 255, 0.5)",
    "rgba(91, 143, 255, 0.5)",
    "rgba(118, 239, 209, 0.5)",
    "rgba(255, 233, 110, 0.5)",
  ];
} else {
  color = [
    "rgba(32, 144, 255, 1)",
    "rgba(97, 210, 199, 1)",
    "rgba(183, 171, 255, 1)",
    "rgba(255, 182, 110, 1)",
    "rgba(32, 144, 255, 0.5)",
    "rgba(97, 210, 199, 0.5)",
    "rgba(183, 171, 255, 0.5)",
    "rgba(255, 182, 110, 0.5)",
  ];
}

let yData = props.chartData.dataY;

const legends = yData.map((e) => e.name);

// 初始化图表
const initChart = () => {
  if (!chartRef.value) return;

  chart = echarts.init(chartRef.value);

  if (!chart) {
    console.error("ECharts 容器未找到");
    return;
  }

  const series = yData.map((element, index) => ({
    smooth: true,
    showSymbol: true,
    symbolSize: 5,
    symbol: "circle",
    name: legends[index],
    type: "line",
    itemStyle: {
      color: "#fff",
      borderColor: color[index],
      borderWidth: 10,
    },
    lineStyle: {
      color: color[index],
      width: 2,
    },
    data: element.val,
    animationDuration: 2800,
    animationEasing: "quadraticOut",
  }));

  let options = {
    tooltip: {
      trigger: "axis",
      confine: true,
      backgroundColor: "rgba(4, 43, 60, 0.8)",
      borderColor: "#1694c7",
      borderWidth: 1,
      textStyle: {
        color: "#fff",
      },
      formatter: function (params) {
        let result = "";
        params.forEach((item) => {
          result += `<div><span style="display:inline-block;margin-right:5px;border-radius:10px;width:10px;height:10px;background-color:${item.borderColor}"></span>${item.seriesName}: ${item.value}</div>`;
        });
        return result;
      },
    },
    legend: {
      show: true,
      data: legends,
      left: "200px",
      textStyle: {
        color: "#ffffff",
      },
      top: 0,
      itemWidth: 9,
      itemHeight: 2,
      icon: "rect",
    },
    grid: {
      left: "6%",
      top: "15%",
      right: "3%",
      bottom: "3%",
      containLabel: true,
    },
    xAxis: [
      {
        type: "category",
        data: xData,
        boundaryGap: true,
        splitLine: { show: false },
        axisLine: {
          show: true,
          lineStyle: {
            color: "rgba(130,144,157,0.1)",
            type: "solid",
          },
        },
        axisLabel: {
          interval: 0,
          rotate: 40,
          color: "#fff",
          fontSize: 14,
        },
        axisTick: {
          show: false,
        },
        splitArea: {
          show: false,
        },
      },
    ],
    dataZoom: [
      {
        xAxisData: 0, //这里是从X轴的0刻度开始
        show: false, //是否显示滑动条
        type: "slider", // 这个 dataZoom 组件是 slider 型 dataZoom 组件
        startValue: 0, // 从头开始。
        endValue: 11, // 一次性展示12个。
      },
    ],
    yAxis: [
      {
        name: "单位：kg CO2/kWh",
        nameTextStyle: {
          fontSize: 14,
          color: "#fff",
          padding: [0, 0, 5, 80],
        },
        nameLocation: "end",
        nameGap: 25,
        splitArea: {
          show: false,
        },
        type: "value",
        splitLine: {
          show: true,
          lineStyle: {
            width: 2,
            type: "solid",
            color: "rgba(130,144,157,0.1)",
          },
        },
        axisLabel: {
          color: "#fff",
          fontSize: 14,
        },
        axisLine: {
          lineStyle: {
            color: "#fff",
          },
        },
        scale: true, //y轴数值自适应 不从0开始
      },
    ],
    series,
  };
  chart.setOption(options);


  window.addEventListener("resize", resizeHandler);
  timer = setInterval(function () {
        if (xData.length < 11) {
          return;
        } else {
          // 每次向后滚动一个，最后一个从头开始。
          if (options.dataZoom[0].endValue == xData.length) {
            options.dataZoom[0].endValue = 11;
            options.dataZoom[0].startValue = 0;
          } else {
            options.dataZoom[0].endValue = options.dataZoom[0].endValue + 1;
            options.dataZoom[0].startValue = options.dataZoom[0].startValue + 1;
            if (options.dataZoom[0].endValue == xData.length) {
              options.dataZoom[0].endValue = 11;
              options.dataZoom[0].startValue = 0;
            }
          }
          chart.setOption(options);
        }
      }, 2000);
  
};

  // 添加响应式支持
  const resizeHandler = () => {
    chart.resize();
  };
// 生命周期钩子
onMounted(() => {
  initChart();
});

// 组件卸载前清理
onBeforeUnmount(() => {
  if (timer) {
    clearInterval(timer);
    timer = null;
  }

  if (chart) {
    chart.dispose();
    chart = null;
  }
   window.removeEventListener("resize", resizeHandler);
});

// 监听 props.chartData 变化，更新图表
watch(
  () => props.chartData,
  (newVal, oldVal) => {
    if (chart) {
      initChart();
    }
  },
  { deep: true }
);
</script>

<style lang="scss" scoped>
.chart-container {
  padding-top: 20px;
  background-color: rgba(29, 52, 81, 0.2); /* 设置图表背景色 */
}
</style>  